<script setup>
import { onShow } from '@dcloudio/uni-app';
import System from '@/utils/system';
import { appStore } from '@/sotre/modules/app';

const { userInfo } = toRefs(appStore());

const $post = inject('$post');
const $put = inject('$put');

const registerForm = ref({
    account: '',
    password: '',
    code: '',
    openid: uni.getStorageSync('OPENID'),
});
const registerRef = ref();
const showPassword = ref(false);
const codeTime = ref(0);
const state = ref(0); // 注册 0 填信息，1填邀请码，2填企业信息
const inviteCode = ref(uni.getStorageSync('inviteCode') || '');
const focus = ref(false);
const tab = ref(0);
const weChat = ref(System.info.uniPlatform === 'mp-weixin');

let codeTimer = null;

onShow(() => {
    tab.value = 0;
    if (userInfo.value.state) {
        state.value = userInfo.value.state;
    }
});

function getCode() {
    if (codeTime.value > 0) return;
    if (!registerForm.value.account || registerForm.value.account.length !== 11) {
        uni.showToast({
            title: '请输入正确的手机号',
            icon: 'none',
        });
        return;
    }
    $post('/auth/platform/smsSend', {
        phone: registerForm.value.account,
    }).then(res => {
        if (res.code === 200) {
            uni.showToast({
                title: '验证码已发送',
                icon: 'success',
            });
            codeTime.value = 60;
            codeTimer = setInterval(() => {
                codeTime.value--;
                if (codeTime.value <= 0) {
                    clearInterval(codeTimer);
                    codeTimer = null;
                }
            }, 1000);
        }
    });
}

function changeTab(e) {
    tab.value = e.index;
    if (e.index === 1) {
        uni.navigateTo({
            url: '/pages/index/company?type=1',
        });
    }
}

function submitInvite() {
    if (!inviteCode.value) {
        return uni.showToast({
            title: '请输入邀请码',
            icon: 'none',
        });
    }
    uni.showLoading({
        title: '提交中...',
        mask: true,
    });
    $put(
        '/platform/users/invite',
        { code: inviteCode.value },
        uni.getStorageSync('TEMP_TOKEN')
    ).then(res => {
        uni.hideLoading();
        if (res.code == 200) {
            const user = res.data.user.platformUsers;
            if (res.data.inviteType == 1 && user.state == 0) {
                uni.setStorageSync('TOKNE', uni.getStorageSync('TEMP_TOKEN'));
                uni.setStorageSync('enterpriseId', user.lastEnterpriseId);
                uni.switchTab({
                    url: '/pages/home/index',
                });
            } else if (res.data.inviteType == 3 || res.data.inviteType == 2) {
                uni.setStorageSync('TOKNE', uni.getStorageSync('TEMP_TOKEN'));
                uni.setStorageSync('enterpriseId', user.lastEnterpriseId);
                uni.switchTab({
                    url: '/pages/home/index',
                });
            } else if (res.data.inviteType == 1) {
                uni.setStorageSync('enterpriseId', user.lastEnterpriseId);
                uni.navigateTo({
                    url: '/pages/index/company?type=1',
                });
            }
            uni.removeStorageSync('inviteCode');
        }
    });
}
function registerFun() {
    registerRef.value.validate().then(({ valid }) => {
        if (valid) {
            uni.showLoading({
                title: '提交中...',
                mask: true,
            });
            $post('/auth/platform/register', {
                str: JSON.stringify(registerForm.value),
                wechat: true,
            }).then(res => {
                uni.hideLoading();
                if (res.code === 200) {
                    state.value = res.data.userInfo.platformUsers.state;
                    uni.setStorageSync('TEMP_USER', res.data.userInfo.platformUsers);
                    uni.setStorageSync('TEMP_TOKEN', res.data.access_token);
                    userInfo.value = res.data.userInfo.platformUsers;
                }
            });
        }
    });
}
</script>

<template>
    <div class="register">
        <u-navbar
            :title="state === 0 ? '注册' : '填写邀请码'"
            :autoBack="true"
            placeholder
        ></u-navbar>
        <div class="box">
            <div class="center">
                <wd-img src="/static/image/logo_person.png" width="200" mode="widthFix"></wd-img>
            </div>
            <template v-if="state === 0">
                <wd-form :model="registerForm" ref="registerRef">
                    <wd-input
                        type="text"
                        v-model="registerForm.account"
                        placeholder="请输入手机号"
                        size="large"
                        prop="account"
                        :rules="[{ required: true, message: '请输入手机号' }]"
                        :maxlength="11"
                    />
                    <wd-input
                        :type="showPassword ? 'text' : 'password'"
                        v-model="registerForm.password"
                        placeholder="请输入密码"
                        size="large"
                        prop="password"
                        :show-password="weChat"
                        :rules="[{ required: true, message: '请输入密码' }]"
                        :maxlength="30"
                    >
                        <template #suffix v-if="!weChat">
                            <wd-icon
                                :name="showPassword ? 'view' : 'eye-close'"
                                size="22px"
                                @click="showPassword = !showPassword"
                            ></wd-icon>
                        </template>
                    </wd-input>
                    <wd-input
                        type="number"
                        v-model="registerForm.code"
                        placeholder="请输入验证码"
                        size="large"
                        prop="code"
                        :rules="[{ required: true, message: '请输入验证码' }]"
                        :maxlength="6"
                    >
                        <template #suffix>
                            <wd-button
                                type="text"
                                :disabled="codeTime > 0"
                                size="small"
                                @click="getCode"
                            >
                                {{ codeTime > 0 ? `${codeTime}s` : '获取验证码' }}
                            </wd-button>
                        </template>
                    </wd-input>
                    <u-button type="warning" size="large" @click="registerFun">立即注册</u-button>
                </wd-form>
            </template>
            <template v-else-if="state === -1 || state === 3">
                <div
                    style="
                        text-align: center;
                        margin: 40px 0;
                        color: #333;
                        font-size: 24px;
                        font-weight: bold;
                    "
                >
                    你好
                </div>
                <u-tabs
                    v-if="tab === 0 && state === -1"
                    :list="[{ name: '有邀请码' }, { name: '无邀请码' }]"
                    :activeStyle="{ color: '#f9702d' }"
                    lineColor="#f9702d"
                    lineWidth="50"
                    @change="changeTab"
                    :current="tab"
                ></u-tabs>
                <div class="invite" :style="{ borderColor: focus ? '#f9702d' : '#e0e0e0' }">
                    <input
                        type="text"
                        placeholder="请输入邀请码"
                        v-model="inviteCode"
                        @focus="focus = true"
                        @blur="focus = false"
                    />
                </div>
                <div class="invite_btn">
                    <u-button type="warning" size="large" @click="submitInvite">提交</u-button>
                </div>
            </template>
        </div>
    </div>
</template>

<style lang="scss" scoped>
.register {
    .center {
        display: flex;
        justify-content: center;
        align-items: center;
    }
    .box {
        padding: 30px 20px;
        .invite {
            margin: 20px;
            padding: 13px 15px;
            border-radius: 4px;
            border: 1px solid #e0e0e0;
            box-sizing: border-box;
            transition: all 0.2s;
        }
        .invite_btn {
            padding: 0 20px;
        }
        :deep(.wd-form) {
            display: flex;
            flex-direction: column;
            padding: 50px 10px;
            .wd-input {
                background: transparent;
                .wd-icon {
                    background: transparent;
                    color: #fb6f2e;
                }
                button {
                    margin: 0;
                    font-weight: bold;
                    font-size: 14px;
                    color: #fb6f2e;
                }
            }
            .tools {
                display: flex;
                align-items: center;
                padding: 10px;
                gap: 20px;
                button {
                    margin: 0;
                    color: #fb6f2e;
                }
            }
            button {
                margin-top: 50px;
            }
        }
        :deep(.u-tabs__wrapper__nav__item__text) {
            font-size: 16px;
        }
    }
}
</style>
